package com.fanhang.samples.redis.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	private static SpringContextUtils instance;
	
	private SpringContextUtils() {
	}
	
	public static SpringContextUtils me() {
		if (instance == null) {
			instance = new SpringContextUtils();
		}
		return instance;
	}
	
	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		applicationContext = ctx;
	}
	
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	public static Object get(String name) {
		return getApplicationContext().getBean(name);
	}
	
	public <T> T get(Class<T> requiredType) {
		return getApplicationContext().getBean(requiredType);
	}
	
	public <T> T get(String name, Class<T> requiredType) {
		return getApplicationContext().getBean(name, requiredType);
	}

}
